package com.ysxsoft.wdg.net;

import android.annotation.SuppressLint;

import com.google.gson.Gson;
import com.ysxsoft.wdg.BuildConfig;
import com.ysxsoft.wdg.net.interceptor.LoggerInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 */
@SuppressLint("StaticFieldLeak")
public class HttpClient {
    private ApiService mApiService;

    private HttpClient() {
//        String cacheFile = MyApplication.getContext().getCacheDir().getAbsolutePath() + File.separator + "data/NetCache";
//        Cache cache = new Cache(new File(cacheFile), 150 * 1024 * 1024);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
//                .addNetworkInterceptor(new CacheInterceptor())//缓存
//                .addInterceptor(new CacheInterceptor())//设置缓存
//                .cache(cache)
                .connectTimeout(20, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//读取超时时间
                .writeTimeout(20, TimeUnit.SECONDS)//写入超时时间
                .retryOnConnectionFailure(true);//重试
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new LoggerInterceptor());//日志
        }
        OkHttpClient client = builder.build();
        Gson gson = new Gson().newBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(UrlHost.HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mApiService = retrofit.create(ApiService.class);
    }

    private static class HttpClientHolder {
        @SuppressLint("StaticFieldLeak")
        private static final HttpClient INSTANCE = new HttpClient();
    }

    public static HttpClient getInstance() {
        return HttpClientHolder.INSTANCE;
    }

    public ApiService getApiService() {
        return mApiService;
    }





}
